/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.inventory;


import com.toedter.calendar.JDateChooser;
import java.awt.Color;
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.awt.event.*;
import java.math.BigDecimal;
import java.util.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

import main.ServicesList;
import model.inventory.AdjDetail;
import model.inventory.AdjMst;
import model.inventory.Item;
import model.publics.Supplier;
import org.apache.log4j.Logger;
import utility.Constants;
import utility.NameValueList;
import utility.StringUtils;
import utility.com.TableCellListener;
import utility.com.TableUtil;
import utility.com.TextComponentUtils;

import view.TransaksiTemplate;
import view.lookup.LookupSimpleFrm;


/**
 *
 * @author Yusup Jauhari Shandi <in.visi>
 */
public final class AdjFrm extends TransaksiTemplate {

    /**
     * Creates new form AdjFrm
     */
    
    private AdjMstTM adjMstTM;
    private AdjMst adjMst;

    private TableCellListener tableCellListener;// = new TableCellListener(grid, DetailAction);
    private ItemListener itemListener = new AdjFrm.OrdersListener();
    private static Logger log = Logger.getLogger(AdjFrm.class);
    private Object oldValue, newValue;
    final JTextField itemCEditor = new JTextField();  
    final JTextField ctnCEditor = new JTextField();    
    final JTextField pcsCEditor = new JTextField();  
    
    private static final int COL_NO     = 0;
    private static final int COL_PLU    = 1;
    private static final int COL_NAMA   = 2;
    private static final int COL_UNIT = 3;
    private static final int COL_STOK   = 4;
    private static final int COL_QTY   = 5;
    private static final int COL_SELISIH   = 6;
    private static final int COL_HARGA  = 7;
    private static final int COL_TOTADJ = 8;
    private static final int COL_TOTSELISIH    = 9;
    
    
    public AdjFrm() {
        initComponents();
         initComponentsRules();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dtpTransDate = new com.toedter.calendar.JDateChooser();
        jLabel1 = new javax.swing.JLabel();
        txtNomor = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        btnNew = new javax.swing.JButton();
        btnDeleteRow = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnPosting = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();
        txtNotes = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        pnlFIlter = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtJenisItem = new javax.swing.JTextField();
        txtSupplier = new javax.swing.JTextField();
        txtNamaItem = new javax.swing.JTextField();
        btnLoad = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        grid = new javax.swing.JTable();
        txtTotalSelisih = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtTotal = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        dtpTransDate.setName("dtpTransDate"); // NOI18N

        jLabel1.setText("Tgl Stok Opname :");

        txtNomor.setName("txtNomor"); // NOI18N

        jLabel6.setText("Nomor SO :");

        jToolBar1.setBackground(new java.awt.Color(255, 51, 51));
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setMaximumSize(new java.awt.Dimension(32767, 20));
        jToolBar1.setSize(this.getWidth(), 50);

        btnNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit_add.png"))); // NOI18N
        btnNew.setText("Tambah");
        btnNew.setFocusable(false);
        btnNew.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });
        jToolBar1.add(btnNew);

        btnDeleteRow.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit_remove.png"))); // NOI18N
        btnDeleteRow.setText("Delete Row");
        btnDeleteRow.setFocusable(false);
        btnDeleteRow.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnDeleteRow.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDeleteRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteRowActionPerformed(evt);
            }
        });
        jToolBar1.add(btnDeleteRow);

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/filesave.png"))); // NOI18N
        btnSave.setText("Save");
        btnSave.setFocusable(false);
        btnSave.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });
        jToolBar1.add(btnSave);

        btnPosting.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit.png"))); // NOI18N
        btnPosting.setText("Posting");
        btnPosting.setFocusable(false);
        btnPosting.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnPosting.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(btnPosting);

        btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/print.png"))); // NOI18N
        btnPrint.setText("Print");
        btnPrint.setFocusable(false);
        btnPrint.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnPrint.setName(""); // NOI18N
        btnPrint.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });
        jToolBar1.add(btnPrint);

        txtNotes.setName("txtNotes"); // NOI18N
        txtNotes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNotesActionPerformed(evt);
            }
        });

        jLabel7.setText("Keterangan :");

        jLabel3.setText("Jenis Item :");

        jLabel2.setText("Supplier :");

        jLabel4.setText("Nama Item :");

        txtJenisItem.setName("txtSupplier"); // NOI18N

        txtSupplier.setName("txtSupplier"); // NOI18N

        txtNamaItem.setName("txtSupplier"); // NOI18N

        btnLoad.setText("Load");
        btnLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlFIlterLayout = new javax.swing.GroupLayout(pnlFIlter);
        pnlFIlter.setLayout(pnlFIlterLayout);
        pnlFIlterLayout.setHorizontalGroup(
            pnlFIlterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlFIlterLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlFIlterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnLoad)
                    .addGroup(pnlFIlterLayout.createSequentialGroup()
                        .addGroup(pnlFIlterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlFIlterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtNamaItem, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
                            .addComponent(txtJenisItem)
                            .addComponent(txtSupplier))))
                .addContainerGap(22, Short.MAX_VALUE))
        );
        pnlFIlterLayout.setVerticalGroup(
            pnlFIlterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlFIlterLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlFIlterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtJenisItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlFIlterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlFIlterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtNamaItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnLoad)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        grid.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        grid.setRowSelectionAllowed(false);
        grid.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                gridKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(grid);

        txtTotalSelisih.setText("jTextField1");
        txtTotalSelisih.setName("txtTotal"); // NOI18N

        jLabel12.setText("Total Selisih:");

        jLabel11.setText("Total Penyesuaian:");

        txtTotal.setText("jTextField1");
        txtTotal.setName("txtTotal"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtTotalSelisih, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel11)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 669, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel11)
                        .addGap(32, 32, 32))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTotalSelisih, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel12))))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(5, 5, 5))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dtpTransDate, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNomor, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(txtNotes, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(pnlFIlter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pnlFIlter, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(dtpTransDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtNomor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel6)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNotes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtNotesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNotesActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNotesActionPerformed

    private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnPrintActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        validasi();
    }//GEN-LAST:event_btnSaveActionPerformed
    
    class GridKeyListener implements KeyListener {
        @Override public void keyTyped(KeyEvent e) {};
        @Override public void keyReleased(KeyEvent e) {};
        
        @Override public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) { 
                case KeyEvent.VK_ENTER:
                    if ((grid.getSelectedRow() == grid.getRowCount()-1) 
                            && grid.getSelectedColumn() == COL_QTY) {
                        adjMst.getAdjDetails().add(new AdjDetail());
                        adjMstTM.fireTableDataChanged(); 
                    }
                    break;
            }        
        };
    }
    
    Action DetailAction = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            TableCellListener tblCellListener = (TableCellListener)e.getSource();
            int row = tblCellListener.getRow();
            int col = tblCellListener.getColumn();
                
            Object oldVal = tblCellListener.getOldValue();
            Object newVal = tblCellListener.getNewValue();
            
            if(oldVal==null) {oldVal="";}
            if(newVal==null) {newVal="";}
                
            if (!oldVal.equals(newValue)) {
                switch (col) {
//                    case COL_QCTN: 
//                        BigDecimal qcrt = TextComponentUtils.parseNumberToBigDecimal((String)newVal);
//                        orderMst.getOrderDetails().get(row).setQtyCrt(qcrt);
//                        calculate(row);
//                        initButtonState(true);
//                        break;
                    case COL_QTY: 
                        BigDecimal qpcs = TextComponentUtils.parseNumberToBigDecimal((String)newVal);
                        adjMst.getAdjDetails().get(row).setQtyReal(qpcs);
                        //calculate(row);
                        initButtonState(true);
                        break;
                }
            }
        }
    };     
    
    class OrdersListener implements ItemListener {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange()==ItemEvent.SELECTED) {
                int id = Integer.parseInt(((NameValueList) e.getItem()).getKey());
                loadData(id);
            }
        }
    }
 
    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        initForm();
    }//GEN-LAST:event_btnNewActionPerformed

    private void gridKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_gridKeyPressed
        // TODO add your handling code here:
         if ((KeyEvent.getKeyText(evt.getKeyCode()).equals("Enter"))&&(grid.getSelectedColumn()==COL_QTY)){            
            addRow();
        }
    }//GEN-LAST:event_gridKeyPressed

    private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnLoadActionPerformed

    private void btnDeleteRowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteRowActionPerformed
        // TODO add your handling code here:
        deleteRow();
    }//GEN-LAST:event_btnDeleteRowActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
       
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AdjFrm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDeleteRow;
    private javax.swing.JButton btnLoad;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnPosting;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnSave;
    private com.toedter.calendar.JDateChooser dtpTransDate;
    private javax.swing.JTable grid;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JPanel pnlFIlter;
    private javax.swing.JTextField txtJenisItem;
    private javax.swing.JTextField txtNamaItem;
    private javax.swing.JTextField txtNomor;
    private javax.swing.JTextField txtNotes;
    private javax.swing.JTextField txtSupplier;
    private javax.swing.JTextField txtTotal;
    private javax.swing.JTextField txtTotalSelisih;
    // End of variables declaration//GEN-END:variables

   

    @Override
    protected void initForm() {
        adjMst = new AdjMst();
        pnlFIlter.setVisible(false);
        txtSupplier.setText("");
        txtJenisItem.setText("");
        txtNamaItem.setText("");
        dtpTransDate.setDate(new Date());
        txtNomor.setText(ServicesList.getSystemNumberingService().getNextNumberDb(Constants.TRANS_ADJUSTMENT, dtpTransDate.getDate()));
        txtNotes.setText("");
        txtTotal.setText("0");
        txtTotalSelisih.setText("0");
        txtTotal.setEnabled(false);
        txtTotalSelisih.setEnabled(false);
        initGrid(adjMst.getAdjDetails());
        initButtonState(false);
    }

    @Override
    protected void saveData() {
        adjMst.setTransNum(txtNomor.getText());
        adjMst.setTransDate(dtpTransDate.getDate());
        adjMst.setNotes(txtNotes.getText());
        if (adjMst.getId()==null){
            adjMst.setInsertedLog(ServicesList.getSystemUserService().getUserIdLog());
        }
        else {
            adjMst.setUpdatedLog(ServicesList.getSystemUserService().getUserIdLog());
        }
        boolean saved = false;
        try{
            saved = ServicesList.getAdjService().save(adjMst);
            
        } catch(Exception ex){
            log.error(ex);
            JOptionPane.showMessageDialog(this, "Data gagal disimpan."
            ,"Error",JOptionPane.ERROR_MESSAGE);
        }
        
        initButtonState(!saved);
    }

    @Override
    protected void validasi() {
        boolean rs =true;
        
       if (rs){
           saveData();
       }
    }

    @Override
    protected void initButtonState(boolean state) {
         btnSave.setEnabled(state);
    }

    @Override
    public void execute(boolean withVisible, int id) {
        setLocationRelativeTo(null);
        initForm();
        if (withVisible) { setVisible(true); }
          
    }
    
    @Override
    public void setVisible(boolean value) {
        super.setVisible(value);
        txtNotes.requestFocusInWindow();
    }

    protected void initGrid(List<AdjDetail> data){
         if(adjMstTM!=null) {adjMstTM=null;}
        
        grid.removePropertyChangeListener(tableCellListener);
        boolean readOnly = false;
        if (adjMst.getStatusId()!=null) {
            readOnly = adjMst.getStatusId() > 0 ? true:false;
        }
        
        adjMstTM = new AdjMstTM(data, readOnly);
        grid.setModel(adjMstTM);
        
        //hanya yg open aja yg bisa edit detail
        if (adjMst.getStatusId()==null || adjMst.getStatusId() == Constants.STATUS_TRANS_OPEN) {
            int idx=0;
            for (AdjDetail detail : data) {
                if (detail.getItem()!=null) {
                    //ItemHpp hpp = ServicesList.getItemHppService().get(detail.getItem().getId(), adjMst.getTransDate());
                   // detail.setItemHpp(hpp);
                    //calculateDiskon(idx);
                    idx++;
                }
            }
            tableCellListener = new TableCellListener(grid, DetailAction);
        }
        
        DefaultTableCellRenderer rightCellRender = new DefaultTableCellRenderer();
        rightCellRender.setHorizontalAlignment(SwingConstants.RIGHT);

        adjMstTM = new AdjMstTM(adjMst.getAdjDetails());
        grid.setModel(adjMstTM);
        
        //set alignment
        grid.getColumnModel().getColumn(COL_NO).setCellRenderer(rightCellRender);
        grid.getColumnModel().getColumn(COL_QTY).setCellRenderer(rightCellRender);
        grid.getColumnModel().getColumn(COL_HARGA).setCellRenderer(rightCellRender);
        grid.getColumnModel().getColumn(COL_SELISIH).setCellRenderer(rightCellRender);
        grid.getColumnModel().getColumn(COL_STOK).setCellRenderer(rightCellRender);
        grid.getColumnModel().getColumn(COL_QTY).setCellRenderer(rightCellRender);
        grid.getColumnModel().getColumn(COL_TOTADJ).setCellRenderer(rightCellRender);
        grid.getColumnModel().getColumn(COL_TOTSELISIH).setCellRenderer(rightCellRender);
        
            
        //cell ony accept number    
        TextComponentUtils.setNumericTextOnly(ctnCEditor);
        TextComponentUtils.setNumericTextOnly(pcsCEditor);
        grid.getColumnModel().getColumn(COL_PLU).setCellEditor(new DefaultCellEditor (itemCEditor));
       // grid.getColumnModel().getColumn(COL_QTY).setCellEditor(new DefaultCellEditor (ctnCEditor));
        grid.getColumnModel().getColumn(COL_QTY).setCellEditor(new DefaultCellEditor (pcsCEditor));
        
        
         grid.getColumnModel().getColumn(COL_NO).setPreferredWidth(3);
        grid.getColumnModel().getColumn(COL_PLU).setPreferredWidth(25);
        grid.getColumnModel().getColumn(COL_NAMA).setPreferredWidth(25);
        grid.getColumnModel().getColumn(COL_STOK).setPreferredWidth(20);
        grid.getColumnModel().getColumn(COL_SELISIH).setPreferredWidth(10);
        grid.getColumnModel().getColumn(COL_QTY).setPreferredWidth(10);
        grid.getColumnModel().getColumn(COL_HARGA).setPreferredWidth(30);
        grid.getColumnModel().getColumn(COL_TOTADJ).setPreferredWidth(40);
        grid.getColumnModel().getColumn(COL_TOTSELISIH).setPreferredWidth(45);
        grid.getColumnModel().getColumn(COL_UNIT).setPreferredWidth(10);
        
        
        //look style
        final TableCellRenderer header = grid.getTableHeader().getDefaultRenderer();
        grid.getTableHeader().setDefaultRenderer(new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                JLabel lbl = (JLabel) header.getTableCellRendererComponent(table, 
                      value, isSelected, hasFocus, row, column);
                lbl.setBorder(BorderFactory.createEmptyBorder(5,1,5,1));   

                switch (column) {
                    case COL_PLU: lbl.setHorizontalAlignment(SwingConstants.LEFT); break;
                    case COL_NAMA: lbl.setHorizontalAlignment(SwingConstants.LEFT); break; 
                  //  case COL_ITEMBONUS: lbl.setHorizontalAlignment(SwingConstants.LEFT); break;
                    default: lbl.setHorizontalAlignment(SwingConstants.RIGHT); break;   
                }
                lbl.setForeground(Color.WHITE);
                lbl.setBackground(Color.DARK_GRAY);
                return lbl;
            }
        });
        grid.setGridColor(Color.LIGHT_GRAY);
    }
    
    @Override
    protected void initGrid() {
       
    }

    @Override
    protected void loadData() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
     
    protected void loadData(long id) {
       initForm();
       adjMst = ServicesList.getAdjService().getAdjMst(id);
       if (adjMst!=null) {modelToForm(adjMst); }
    }

    @Override
    protected void posting() {
        boolean saved = false;
        try{
            adjMst.setStatusId(Constants.STATUS_TRANS_POSTED);
            adjMst.setUpdatedLog(ServicesList.getSystemUserService().getUserIdLog());
            saved = ServicesList.getAdjService().save(adjMst);
        } catch(Exception ex){
            log.error(ex);
            JOptionPane.showMessageDialog(this, "Data gagal Posting.", "Error",JOptionPane.ERROR_MESSAGE);
        }
        
         if (saved) { initInputState(); }
    }

    @Override
    protected void initComponentsRules() {
        btnNew.registerKeyboardAction(btnNew.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
         
        btnPosting.registerKeyboardAction(btnPosting.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);

        
        btnSave.registerKeyboardAction(btnSave.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        
        btnPrint.registerKeyboardAction(btnPrint.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        
        
        itemCEditor.setName("itemCEditor");
        pcsCEditor.setName("pcsCEditor");
        txtNotes.addKeyListener(new view.inventory.AdjFrm.ActionKeyListener());
        itemCEditor.addKeyListener(new view.inventory.AdjFrm.ActionKeyListener());
        txtNomor.addKeyListener(new ActionKeyListener());
        txtNotes.addFocusListener(new view.inventory.AdjFrm.ActionFocusGained());
        itemCEditor.addFocusListener(new view.inventory.AdjFrm.ActionFocusGained());
        txtNomor.addFocusListener(new ActionFocusGained());

        TableUtil.setTableActionKeyMap(grid);
        grid.addKeyListener( new GridKeyListener());
    }
    
    private  void addRow(){ //Add Row
                
        AbstractTableModel md = (AbstractTableModel) grid.getModel();
        
        ((AdjMstTM)md).add(new AdjDetail());
        grid.setModel(md);        
    }
    
    
     
     private void lookupMaster(int purpose, String param) {
        Object object = new LookupSimpleFrm().execute(purpose, param);
        if (object != null) { setMaster(purpose, object); }
    }
     
      private void setMaster(int purpose, Object object) {
         if (object != null) {
            switch (purpose) {
                case Constants.LOOKUP_ITEM:
                    int row = grid.getSelectedRow();
                    //Item item = (Item)object;
                    int itemId = ((Item) object).getId();
                    adjMst.getAdjDetails().get(row).setItem((Item) object);
                    adjMst.getAdjDetails().get(row).getId().setItemId(itemId);
                   // grid.setValueAt(item.getPlu(), row, COL_PLU);    
                    //itemCEditor.setText(item.getPlu());
//                    adjMst.getAdjDetails().get(row).setItem(item);
                    adjMstTM.fireTableCellUpdated(row, row);
                    //cari juga hpp
                    break;
                      case Constants.LOOKUP_SUPPLIER:
//                    adjMst.setSupplier((Supplier) object);
                    txtSupplier.setText(((Supplier) object).getNama());
//                            adjMst.getSupplier().getKode().concat(" (")
//                            .concat(adjMst.getSupplier().getNama())
//                            .concat(")"));
//                    
                    break;
              
                
                default: break;    
            }
        }
    }
     private void getMaster(int purpose, String kode) {
        switch (purpose) {
           case Constants.LOOKUP_ITEM:
                Item item = ServicesList.getItemService().getItem(kode);
                if (item != null) {setMaster(purpose, item); }
                else { lookupMaster(purpose, itemCEditor.getText()); }
                break;
               
           case Constants.LOOKUP_SUPPLIER:
                Supplier suplier = ServicesList.getSupplierService().getSupplier(kode);
                if (suplier != null) {setMaster(purpose, suplier); }
                else { lookupMaster(purpose, txtSupplier.getText()); }
                break;
                              
           default: break;    
        }
    }
     
      private void moveNext() {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.focusNextComponent();
    }

    private void deleteRow() {
        int rowCount = grid.getRowCount();
        int row = grid.getSelectedRow();
        
        if (rowCount==1) {
            AdjDetail emptyData = new AdjDetail();
            adjMst.getAdjDetails().set(row, emptyData);
            adjMstTM.fireTableRowsUpdated(row, row);
        } else {
            adjMst.getAdjDetails().remove(row);
            adjMstTM.fireTableRowsDeleted(row, row);
        }
        initInputState();
        initButtonState(true);
    }

    private void initInputState() {
        long transId = adjMst.getId()==null ? 0:adjMst.getId();
        Integer statusId = adjMst.getStatusId()==null ? 0:adjMst.getStatusId();
        //long revisiId = adjMst.getRevisedId()==null ? 0:adjMst.getRevisedId();
  
        txtNotes.setEnabled(statusId==0);
        txtSupplier.setEnabled(statusId==0);
        dtpTransDate.setEnabled(statusId==0);
       
        btnPrint.setEnabled(transId>0);
        btnSave.setEnabled(transId==0 && statusId==Constants.STATUS_TRANS_OPEN);
        btnPosting.setEnabled(transId>0 && statusId==Constants.STATUS_TRANS_OPEN);
        //btnClose.setEnabled(transId>0 && statusId<Constants.STATUS_TRANS_CLOSED);
        //btnRevisi.setEnabled(transId>0 && statusId==Constants.STATUS_TRANS_POSTED);
        btnDeleteRow.setEnabled(statusId==Constants.STATUS_TRANS_OPEN);
    }

    private void modelToForm(AdjMst data) {
       txtNomor.setText(data.getTransNum());
       dtpTransDate.setDate(data.getTransDate());
//        if (data.getRevisedId() != null) {
//            String transNum = ServicesList.getOrderService().getTransNum(data.getRevisedId());
//            txtRevisi.setText(transNum);
//        }
        
        //txtSupplier.setText(data.getSupplier().getNama());
        txtNotes.setText(data.getNotes());
        txtTotal.setText(StringUtils.formatNumber(data.getTotalAsal()));
        txtTotalSelisih.setText(StringUtils.formatNumber(data.getTotalSelisih()));
        initGrid(data.getAdjDetails());
        initInputState();
    }
      
      class ActionKeyListener implements KeyListener {
        @Override public void keyTyped(KeyEvent e) {} 
        @Override public void keyReleased(KeyEvent e) {}
        @Override public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) { 
                case KeyEvent.VK_F2: 
                    switch(e.getComponent().getName()) {
                        case "txtSupplier": 
                            lookupMaster(Constants.LOOKUP_SUPPLIER, txtSupplier.getText()); 
                            break;
                        case "itemCEditor": 
                            lookupMaster(Constants.LOOKUP_ITEM, itemCEditor.getText()); 
                            break;
                    };
                break;  
                
                case KeyEvent.VK_ENTER: 
                    switch(e.getComponent().getName()) {
                        case "itemCEditor": 
                            newValue = itemCEditor.getText();
                            if (!newValue.equals(oldValue)) { getMaster(Constants.LOOKUP_ITEM, itemCEditor.getText()); }
                            break;
                          case "txtSupplier": 
                            newValue = txtSupplier.getText();
                            if (!newValue.equals(oldValue)) { getMaster(Constants.LOOKUP_SUPPLIER, txtSupplier.getText()); }
                            else {moveNext();}
                            break;   
                       
                       default: moveNext(); break;
                    };
                break;      
            }
        }
    }
    
    class ActionFocusGained implements FocusListener {
        @Override public void focusGained(FocusEvent e) { 
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { oldValue = ((JTextField) componen).getText();
            }else if (componen instanceof JComboBox) { oldValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { oldValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { oldValue = ((JTextArea) componen).getText(); 
            }else if (componen instanceof JDateChooser) { oldValue = ((JDateChooser) componen).getDate(); }
        }
        
        @Override public void focusLost(FocusEvent e) {
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { newValue = ((JTextField) componen).getText();
            }else if (componen instanceof JComboBox) { newValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { newValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { newValue = ((JTextArea) componen).getText(); 
            }else if (componen instanceof JDateChooser) { newValue = ((JDateChooser) componen).getDate(); }
            
            if (!newValue.equals(oldValue)) { initButtonState(true); }
        }
    }
    
    
    private void syncronizeDetail(){
        List<Integer> emptyItem = new ArrayList<>();
        
        for (int i=0; i<adjMst.getAdjDetails().size(); i++) {
            if (adjMst.getAdjDetails().get(i).getItem()==null) {
                emptyItem.add(i);
            }
        }
        
        for (Integer i: emptyItem) {
            int idx = i;
            adjMst.getAdjDetails().remove(idx);
        }
    }
    
}
